from fastapi import APIRouter, Depends, HTTPException , Query
from sqlalchemy.orm import Session
from crud import user as crud_user
from schemas import user as schema_user
from schemas import match as schema_match
from utils.database import SessionLocal
from crud import match as crud_match
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from typing import Annotated
from fastapi import Response
from fastapi.responses import JSONResponse
from fastapi.responses import FileResponse
# 新增导入

from utils.security import verify_password, create_access_token ,revoke_old_tokens ,validate_token
from utils.strategy import Strategy


router = APIRouter()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@router.get("/user")
async def user_page():
    return FileResponse("static/user.html")

@router.get("/report")
async def user_page():
    return FileResponse("static/report.html")

@router.post("/users/", response_model=schema_user.User)
def create_user(user: schema_user.UserCreate, db: Session = Depends(get_db)):
    db_user = crud_user.get_user_by_username(db, username=user.username)
    if db_user:
        raise HTTPException(status_code=400, detail="Username already registered")
    return crud_user.create_user(db, user=user)

@router.get("/users/", response_model=list[schema_user.User])
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    users = crud_user.get_users(db, skip=skip, limit=limit)
    return users

@router.get("/users/{user_id}", response_model=schema_user.User)
def read_user(user_id: int, db: Session = Depends(get_db)):
    db_user = crud_user.get_user(db, user_id=user_id)
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return db_user

@router.put("/users/{user_id}", response_model=schema_user.User)
def update_user(user_id: int, user: schema_user.UserCreate, db: Session = Depends(get_db)):
    db_user = crud_user.update_user(db, user_id, user)
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return db_user

@router.get("/matchs/",response_model=list[schema_match.Match])
def read_matchs( page: int = Query(1, ge=1), limit: int = Query(10, ge=1),db: Session = Depends(get_db)):
    skip = (page - 1) * limit
    matchs = crud_match.get_multi(db, skip=skip, limit=limit)
    for match in matchs:
        bs = Strategy.get_bs(match.weight)
        match.weight = bs
    return matchs


@router.post("/token")
async def login_for_access_token(
        response: Response,
        form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
        db: Session = Depends(get_db)
):
    # 1. 验证用户名
    user = crud_user.get_user_by_username(db, username=form_data.username)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )

    # 2. 验证密码 左边是正常值，右边是hash
    if not verify_password(form_data.password, user.password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )
    revoke_old_tokens(user.username)
    # 3. 生成访问令牌
    access_token = create_access_token(
        user.username
    )
    return {"token": access_token}

# 受保护的路由
@router.get("/protected")
async def get_protected_data(
    payload: dict = Depends(validate_token)  # 核心使用点
):
    """
    该路由要求有效 Token 才能访问
    """
    username = payload["sub"]
    return {
        "message": "访问成功",
        "username": username
    }

